/*
 * @author zei, QQ:77132995, email:kazeik@163.com
 * 2022/3/7 17:15
 * 类说明:
 */

import 'dart:convert';
import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:file_picker/file_picker.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/content_data_import_entity.dart';
import 'package:finance_app/src/entities/data_import_entity.dart';
import 'package:finance_app/src/utils/file_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as path;

class ContactDataImportProvider extends BaseProvider {
  List<DataImportEntity> _importItems;
  String _uploadFileName;

  List<DataImportEntity> get importItems => _importItems;

  ContentDataImportEntity _contentDatas;

  File _selectFile;

  ContentDataImportEntity get contentDatas => _contentDatas;

  set uploadFileName(String value) {
    _uploadFileName = value;
    update();
  }

  String get uploadFileName => _uploadFileName;

  set importItems(List<DataImportEntity> value) {
    _importItems = value;
    update();
  }

  void downloadTemplateFile() async {
    obtainContext?.call((context) async {
      BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
      File file = await FileUtils.getExcelTemplate();
      await FileUtils.downloadExcelTemplate(file.path, onReceiveProgress: (progress, count) {
        if (progress == count) {
          Navigator.pop(context);
        }
      });
    });
  }

  void uploadTemplateFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xls', 'xlsx'],
    );
    if (result != null) {
      _selectFile = File(result.files.single.path);
      obtainContext?.call((context) async {
        BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
        await post(
            _uploadExcelFile(_selectFile.path, onSendProgress: (progress, count) {
              if (progress == count) {
                Navigator.pop(context);
              }
            }), onSuccess: (result) {
          logger.d("返回的数据1 = $result}");
          var datas = result.data['data'];
          if (datas != null) {
            _contentDatas = ContentDataImportEntity.fromJson(datas);
            _importItems = contentDatas.dataMapped;
          }
          uploadFileName = _selectFile.path.substring(_selectFile.path.lastIndexOf("/") + 1, _selectFile.path.length);
        }, onError: (code, msg, err, stackTree) {
          logger.d("返回的数据error = $code | $msg | ${err.toString()}");
          showDeleteInfoBottomSheet(context, S.current.file_upload_fail, msg, onDelete: () {
            Navigator.pop(context);
            uploadTemplateFile();
          }, sureBtnText: S.current.choose_again, cancelText: S.current.cancel);
        });
      });
    }
  }

  Future<Response> _uploadExcelFile(String filePath, {ProgressCallback onSendProgress, bool import = false}) async {
    final file = await BaseConfig.httpBase.formFile(filePath, path.basename(filePath));

    return BaseConfig.httpBase.postForm('/api/contacts/excel', {'file': file, "is_import": import}, onSendProgress: onSendProgress);
  }

  void deleteSelectFile() {
    _contentDatas = null;
    _importItems.clear();
    _importItems = null;
    uploadFileName = "";
  }

  showConfirmImport(BuildContext context, {VoidCallback onConfirm, VoidCallback onCancel}) =>
      showDeleteInfoBottomSheet(context, S.current.confirm_import, S.current.once_imported, onDelete: () {
        Navigator.pop(context);
        obtainContext?.call((context) async {
          BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
          await post(
              _uploadExcelFile(_selectFile.path, import: true, onSendProgress: (progress, count) {
                if (progress == count) {
                  Navigator.pop(context);
                }
              }), onSuccess: (result) {
            logger.d("返回的数据2 = $result}");
            var datas = result.data['code'];
            if (datas != 1) {
              showDeleteInfoBottomSheet(context, S.current.file_upload_fail, S.current.file_format_is_not_supported, onDelete: () {
                Navigator.pop(context);
                uploadTemplateFile();
              }, sureBtnText: S.current.choose_again, cancelText: S.current.back_to_screen);
            } else {
              showSuccessTipBottomSheet(context, S.current.you_data_have_ben_imported_successfully);
            }
          });
        });
      }, onCancel: onCancel, sureBtnText: S.current.import, cancelText: S.current.cancel);

  @override
  Future get dataFuture => null;
}
